<?php
    /*
    * Copyright (c) 2007, Osuvaldo Ramos
    * 
    * All rights reserved.
    * 
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are
    * met:
    *
    *    * Redistributions of source code must retain the above copyright
    *      notice, this list of conditions and the following disclaimer.
    *    * Redistributions in binary form must reproduce the above copyright
    *      notice, this list of conditions and the following disclaimer in the
    *      documentation and/or other materials provided with the distribution.
    *    * Neither the name of the CoreTech nor the names of its
    *      contributors may be used to endorse or promote products derived from
    *      this software without specific prior written permission.
    * 
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
    * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    * 
    * $Id: Console.php 2 2008-01-21 02:48:28Z xdracox $
    */
    
    if ( !defined('BNETCS') || !defined('ROOT') ) exit();
    
    include_once ROOT.'/mods/RankSystem/'.$CONF['mods']['ranksystem']['name'].
        '.php';
    
    class Console
    {
        function Console()
        {
            // empty D:
        }
        
        function display()
        {
            global $smarty, $auth;
            
            $rs = new RankSystem();
            
            $actions = array();
            
            // assign actions available for everyone
            $actions[] = array
            (
                'text' => 'Change Password',
                'addr' => 'console.php?a=cp'
            );
            
            $member_id = $auth->getAuthData('member_id');
            
            if ( $rs->canRecruit($member_id) )
            {
                $actions[] = array
                (
                    'text' => 'New Recruit',
                    'addr' => 'console.php?a=rc'
                );
            }
            
            if ( $rs->canPromote($member_id) )
            {
                $actions[] = array
                (
                    'text' => 'Give Promotion',
                    'addr' => 'console.php?a=pr'
                );
            }
            
            if ( $rs->canDemote($member_id) )
            {
                $actions[] = array
                (
                    'text' => 'Give Demotion',
                    'addr' => 'console.php?a=de'
                );
            }
            
            if ( $rs->getRank($member_id) >= RANK_GENERAL )
            {
                $actions[] = array
                (
                    'text' => 'Change Rank',
                    'addr' => 'console.php?a=cr'
                );
            }
            
            if ( sizeof($actions) % 2 == 1 )
            {
                $actions[] = array('text' => '', 'addr' => '#');
            }
            
            $smarty->assign('actions', $actions);
            $smarty->display('console.tpl');
        }
        
        function consoleStart()
        {
            global $smarty;
            $smarty->display('console_start.tpl');
        }
        
        function consoleEnd()
        {
            global $smarty;
            $smarty->display('console_end.tpl');
        }
        
        function displayChangePass()
        {
            global $smarty, $auth, $CONF, $mdb2;
            
            // I HATE MAGIC QUOTES
            foreach ( $_POST as $key => $val )
            {
                $_POST[$key] = get_magic_quotes_gpc
                    ? $_POST[$key]
                    : addslashes($_POST[$key]);
            }
            
            if ( isset($_POST['oldpass']) && isset($_POST['newpass1'])
                && isset($_POST['newpass2']) )
            {
                $old = md5(salt_password($_POST['oldpass'],
                    $CONF['auth']['salt1'], $CONF['auth']['salt2']));
                
                // retrieved the stored password
                $sql = sprintf('SELECT member_password
                    FROM bnetcs_members
                    WHERE member_id = %d', $auth->getAuthData('member_id'));
                $result = $mdb2->query($sql);
                $row = $result->fetchRow();
                $stored = $row['member_password'];
                
                if ( $old == $stored
                    && $_POST['newpass1'] == $_POST['newpass2'] )
                {
                    
                    $_SESSION['notices'] = array();
                    $_SESSION['notices'][] = 'Successfully changed password.';
                    
                    $newpass = salt_password($_POST['newpass1'],
                        $CONF['auth']['salt1'], $CONF['auth']['salt2']);
                    
                    $auth->changePassword($auth->getUsername(), $newpass);
                    
                    header('Location: console.php');
                }
                else
                {
                    $_SESSION['errors'] = array();
                    $msg = 'Failed to change your password, please try again.';
                    $_SESSION['errors'][] = $msg;
                    header('Location: console.php?a=cp');
                }
            }
            else
            {   
                display_header();
                $smarty->display('changepass.tpl');
                display_footer();
            }
        }
        
        function displayRecruitment()
        {
            global $mdb2, $smarty, $auth, $CONF;
            
            $rs = new RankSystem();
            
            if ( !$rs->canRecruit($auth->getAuthData('member_id')) )
            {
                $_SESSION['errors'] = array();
                $_SESSION['errors'][] = 'Sorry, you cannot recruit.';
                header('Location: console.php');
                return;
            }
            
            // I HATE MAGIC QUOTES
            foreach ( $_POST as $key => $val )
            {
                $_POST[$key] = get_magic_quotes_gpc
                    ? $_POST[$key]
                    : addslashes($_POST[$key]);
            }
            
            if ( isset($_POST['member_name']) )
            {
                $member_name = htmlentities($_POST['member_name']);
                
                $_SESSION['errors'] = array();
                $_SESSION['notices'] = array();
                
                if ( !valid_member_name($member_name) )
                    $_SESSION['errors'][] = 'That is not a valid member name.';
                
                $sql = sprintf('SELECT *
                    FROM bnetcs_members
                    WHERE member_login = "%s"', $member_name);
                $result = $mdb2->query($sql);
                if ( $result->numRows() > 0 )
                    $_SESSION['errors'][]='That member name is already in use.';
                
                if ( sizeof($_SESSION['errors']) > 0 )
                {
                    header('Location: console.php?a=rc');
                    exit();
                }
                
                $plain_pw = generate_password();
                $pw = salt_password($plain_pw, $CONF['auth']['salt1'],
                    $CONF['auth']['salt2']);
                
                $add = array('member_join_date' => time());
                
                $auth->addUser($member_name, $pw, $add);
                
                // get the new member's id
                $sql = sprintf('SELECT member_id
                    FROM bnetcs_members
                    WHERE member_login = "%s"', $member_name);
                $result = $mdb2->query($sql);
                $row = $result->fetchRow();
                RankSystem::addUser($row['member_id']);
                
                $_SESSION['notices'][] = 'New member added successfully with'
                    .' the password '.$plain_pw;
                
                header('Location: console.php');
            }
            else
            {
                display_header();
                $smarty->display('recruitment.tpl');
                display_footer();
            }
        }
        
        function displayPromotion()
        {
            global $mdb2, $smarty, $auth, $CONF;
            
            $mid = $auth->getAuthData('member_id');
            
            $rs = new RankSystem();
            
            if ( !$rs->canPromote($mid) )
            {
                $_SESSION['errors'] = array();
                $_SESSION['errors'][] = 'Sorry, you cannot give promotions.';
                header('Location: console.php');
                return;
            }
            
            // I HATE MAGIC QUOTES
            foreach ( $_POST as $key => $val )
            {
                $_POST[$key] = get_magic_quotes_gpc
                    ? $_POST[$key]
                    : addslashes($_POST[$key]);
            }
            
            if ( isset($_POST['member_id']) )
            {
                $other_mid = intval($_POST['member_id']);
                
                // get the user's current rank
                $rank_level = $rs->getRank($other_mid);
                
                if ( $rank_level + 1 <= $rs->maxPromotionRank($mid) )
                {
                    $rs->givePromotion($other_mid);
                    
                    $_SESSION['notices'] = array();
                    $_SESSION['notices'][] =
                        'You have successfully given a promotion.';
                }
                else
                {
                    $_SESSION['errors'] = array();
                    $_SESSION['errors'][] = 'You cannot promote that member.';
                }
                
                header('Location: console.php');
            }
            else
            {
                display_header();
                
                // build a list of eligible promotees
                $max_rank = $rs->maxPromotionRank($mid);
                $eligible = array();
                
                $sql = sprintf('SELECT *
                    FROM bnetcs_defaultrs_ranks
                    WHERE rank_level <= %d
                    ORDER BY rank_level
                        DESC', $max_rank);
                $rank_result = $mdb2->query($sql);
                
                while ( $rank_row = $rank_result->fetchRow() )
                {
                    $sql = sprintf('SELECT *
                        FROM bnetcs_defaultrs_member_ranks
                        WHERE rank_id = %d', $rank_row['rank_id']);
                    $mid_result = $mdb2->query($sql);
                    
                    while ( $mid_row = $mid_result->fetchRow() )
                    {
                        $sql = sprintf('SELECT *
                            FROM bnetcs_members
                            WHERE member_id = %d', $mid_row['member_id']);
                        $member_result = $mdb2->query($sql);
                        $member_row = $member_result->fetchRow();
                        
                        $eligible[] = array
                        (
                            'id' => $member_row['member_id'],
                            'name' => $member_row['member_login'],
                            'rank' => $rank_row['rank_name']
                        );
                    }
                }
                
                $smarty->assign('eligible', $eligible);
                $smarty->display('givepromo.tpl');
                display_footer();
            }
        }
        
        function displayDemotion()
        {
            global $mdb2, $auth, $smarty;
            
            $mid = $auth->getAuthData('member_id');
            
            $rs = new RankSystem();
            
            if ( !$rs->canDemote($mid) )
            {
                $_SESSION['errors'] = array();
                $_SESSION['errors'][] = 'Sorry, you cannot give demotions.';
                header('Location: console.php');
                return;
            }
            
            // I HATE MAGIC QUOTES
            foreach ( $_POST as $key => $val )
            {
                $_POST[$key] = get_magic_quotes_gpc
                    ? $_POST[$key]
                    : addslashes($_POST[$key]);
            }
            
            if ( isset($_POST['member_id']) )
            {
                $other_mid = intval($_POST['member_id']);
                
                $rank_level = $rs->getRank($other_mid);
                
                if ( $rank_level > 1
                    && $rank_level <= $rs->maxDemotionRank($mid) )
                {
                    $rs->giveDemotion($other_mid);
                    
                    $_SESSION['notices'] = array();
                    $_SESSION['notices'] =
                        'You have successfully given a demotion';
                }
                else
                {
                    $_SESSION['errors'] = array();
                    $_SESSION['errors'][] = 'You cannot demote that member.';
                }
                
                header('Location: console.php');
            }
            else
            {
                display_header();
                
                // get a list of eligible demotees
                $max_rank = $rs->maxDemotionRank($mid);
                
                $eligible = array();
                
                $ranks = $rs->getAllRanks($max_rank);
                $lim = sizeof($ranks);
                
                for ( $i = 0; $i < $lim; ++$i )
                {
                    $members = $rs->getMembersWithRank($ranks[$i]['id']);
                    $eligible = array_merge($eligible, $members);
                }
                
                $smarty->assign('eligible', $eligible);
                $smarty->display('givedemo.tpl');
                
                display_footer();
            }
        }
        
        function displayChangeRank()
        {
            global $auth, $smarty;
            
            $rs = new RankSystem();
            $mid = $auth->getAuthData('member_id');
            
            if ( $rs->getRank($mid) < RANK_GENERAL )
            {
                $msg = 'You cannot change ranks.';
                $_SESSION['errors'][] = array($msg);
                header('Location: console.php');
                return;
            }
            
            if ( isset($_POST['member_id']) && isset($_POST['new_rank_id']) )
            {
                $other_mid = intval($_POST['member_id']);
                $rank_id = intval($_POST['new_rank_id']);
                
                $rs->setRank($other_mid, $rank_id);
                
                $msg = 'Member rank changed successfully.';
                $_SESSION['notices'] = array($msg);
                header('Location: console.php');
            }
            else
            {
                $all_members = array();
                
                $ranks = $rs->getAllRanks(RANK_COMMANDER - 1);
                $lim = sizeof($ranks);
                
                for ( $i = 0; $i < $lim; ++$i )
                {
                    $rank_id = $ranks[$i]['id'];
                    $members = $rs->getMembersWithRank($rank_id);
                    $all_members = array_merge($all_members, $members);
                }
                
                $smarty->assign('members', $all_members);
                $smarty->assign('ranks', $ranks);
                
                display_header();
                $smarty->display('changerank.tpl');
                display_footer();
            }
        }
    }
?>
